﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Mocola.BLL;
using Mocola.Model;
using Mocola.Web;
using Mocola.Security;
using Mocola.Common;
using System.Web.Security;
using System.Data.Common;

namespace Mocola.Net.Web
{
    public partial class newarticle : System.Web.UI.Page
    {
        private string info = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            //创建JavaScript
            info = "<script type=\"text/javascript\"> window.parent.MochaUI.updateContent({";
            info += "'element': window.parent.$('mainPanel'),";
            info += "'loadMethod': 'iframe',";
            info += "'url': 'articlelist.aspx',";
            info += "'title': '档案管理制度和流程',";
            info += "'scrollbars': false,";
            info += "'padding': { top: 0, right: 0, bottom: 0, left: 0 }";
            info += "});</script>";
            //if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "myName"))
            //{
            //    //动态注册JavaScript
            //    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "myName", info, true);
            //}

            if (!IsPostBack)
            {
                BindData();
            }
        }

        private void BindData()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ArticleID"]))
            {
                string ArticleID = Request.QueryString["ArticleID"].ToString();

                string sql = "SELECT * FROM Moc_Articles " +
                             "WHERE ArticleID=" + ArticleID;

                DataSet dtUsers = Databases.MocolaNet.ExecuteDataSet(CommandType.Text, sql);

                if (dtUsers.Tables[0].Rows.Count == 1)
                {
                    txtBiaoTi.Text = dtUsers.Tables[0].Rows[0]["Title"].ToString();
                    txtFaBuRiQi.Text = DateTime.Parse(dtUsers.Tables[0].Rows[0]["Created"].ToString()).ToShortDateString();
                    txtFaBuZhe.Text = dtUsers.Tables[0].Rows[0]["Author"].ToString();
                    ddlFenLei.SelectedValue = dtUsers.Tables[0].Rows[0]["Category"].ToString();
                    FCKeditor1.Value = dtUsers.Tables[0].Rows[0]["Content"].ToString();
                }
            }
            else
            {
                txtFaBuRiQi.Text = DateTime.Now.ToShortDateString();
                CustomIdentity identity = this.Page.User.Identity as CustomIdentity;
                txtFaBuZhe.Text = identity.FullName;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (txtBiaoTi.Text.Trim() == string.Empty)
            {
                Alert.Show("必须输入文章标题！");
                txtBiaoTi.Focus();
                return;
            }

            if (txtFaBuRiQi.Text.Trim() == string.Empty)
            {
                Alert.Show("必须输入发布日期！");
                txtFaBuRiQi.Focus();
                return;
            }

            DateTime dt;
            try
            {
                dt = DateTime.Parse(txtFaBuRiQi.Text.Trim());
            }
            catch
            {
                Alert.Show("请输入正确的发布日期！");
                txtFaBuRiQi.Focus();
                return;
            }

            MembershipCreateStatus status = new MembershipCreateStatus();
            DbTransaction transaction = Databases.MocolaNet.BeginTransaction(IsolationLevel.ReadCommitted);

            if (string.IsNullOrEmpty(Request.QueryString["ArticleID"]))
            {
                try
                {
                    int nID = Databases.MocolaNet.Insert(Moc_ArticlesInfo.Moc_Articles)
                                .AddColumn(Moc_ArticlesInfo.Moc_Articles.Title, txtBiaoTi.Text.Trim())
                                .AddColumn(Moc_ArticlesInfo.Moc_Articles.Created, dt.ToShortDateString())
                                .AddColumn(Moc_ArticlesInfo.Moc_Articles.Category, ddlFenLei.SelectedValue)
                                .AddColumn(Moc_ArticlesInfo.Moc_Articles.Author, txtFaBuZhe.Text.Trim())
                                .AddColumn(Moc_ArticlesInfo.Moc_Articles.Content, FCKeditor1.Value)
                                .SetTransaction(transaction)
                                .ExecuteReturnAutoIncrementID(Moc_ArticlesInfo.Moc_Articles.ArticleID);

                    bool blTrees = false;

                    if (nID != -1)
                    {
                        blTrees = true;
                    }

                    if (blTrees)
                    {
                        Alert.Show("保存成功!");
                        status = MembershipCreateStatus.Success;
                        //Response.Write("<script>location.replace('articlelist.aspx');</script>");
                        //Response.Write("<script>updateParent();</script>");
                        if (!Page.ClientScript.IsStartupScriptRegistered("UpdateParent"))
                        {
                            //动态注册并执行JavaScript
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "UpdateParent", info);
                        }

                    }
                    else
                    {
                        Alert.Show("保存失败!");
                        status = MembershipCreateStatus.ProviderError;
                    }
                }
                catch (Exception ex)
                {
                    Alert.Show(ex.Message);
                    status = MembershipCreateStatus.ProviderError;
                }
                finally
                {
                    if (status == MembershipCreateStatus.Success)
                        transaction.Commit();
                    else
                        transaction.Rollback();
                    Databases.MocolaNet.CloseConnection(transaction);
                }
            }
            else
            {
                try
                {
                    int ArticleID = Convert.ToInt32(Request.QueryString["ArticleID"]);
                    bool bUpdated = Databases.MocolaNet.Update(Moc_ArticlesInfo.Moc_Articles)
                                .AddColumn(Moc_ArticlesInfo.Moc_Articles.Title, txtBiaoTi.Text.Trim())
                                .AddColumn(Moc_ArticlesInfo.Moc_Articles.Created, dt.ToShortDateString())
                                .AddColumn(Moc_ArticlesInfo.Moc_Articles.Category, ddlFenLei.SelectedValue)
                                .AddColumn(Moc_ArticlesInfo.Moc_Articles.Author, txtFaBuZhe.Text.Trim())
                                .AddColumn(Moc_ArticlesInfo.Moc_Articles.Content, FCKeditor1.Value)
                                    .Where(Moc_ArticlesInfo.Moc_Articles.ArticleID == ArticleID)
                                    .SetTransaction(transaction)
                                    .Execute() == 1;

                    if (bUpdated)
                    {
                        Alert.Show("更新成功!");
                        status = MembershipCreateStatus.Success;
                        //Response.Write("<script>location.replace('articlelist.aspx');</script>");
                        //Response.Write("<script>updateParent();</script>");
                        if (!Page.ClientScript.IsStartupScriptRegistered("UpdateParent"))
                        {
                            //动态注册并执行JavaScript
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "UpdateParent", info);
                        }
                    }
                    else
                    {
                        Alert.Show("更新失败!");
                        status = MembershipCreateStatus.ProviderError;
                    }
                }
                catch (Exception ex)
                {
                    Alert.Show(ex.Message);
                    status = MembershipCreateStatus.ProviderError;
                }
                finally
                {
                    if (status == MembershipCreateStatus.Success)
                        transaction.Commit();
                    else
                        transaction.Rollback();
                    Databases.MocolaNet.CloseConnection(transaction);
                }
            }
        }
    }
}
